﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NGinnBPM.Lib.Interfaces;
using NGinnBPM.Services;
using NGinnBPM.Runtime;
using System.IO;
using Newtonsoft.Json;
using NGinnBPM.Lib.Schema;
using NGinnBPM.Lib.Services;
using NLog;
using Newtonsoft.Json.Linq;
using NGinnBPM.MessageBus;

namespace NGinnBPM.Services.Persistence
{
    public class SimpleTaskSerializer : ITaskInstanceSerializer
    {
        private JsonSerializer _ser;

        public SimpleTaskSerializer()
        {
            
            _ser = new JsonSerializer();
            
            _ser.TypeNameHandling = TypeNameHandling.Objects;
            _ser.Converters.Add(new Newtonsoft.Json.Converters.IsoDateTimeConverter());
            _ser.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
            _ser.NullValueHandling = NullValueHandling.Ignore;
            _ser.MissingMemberHandling = MissingMemberHandling.Ignore;
            //ser.ObjectCreationHandling = ObjectCreationHandling.Replace;
        }
        public void SerializeTaskInstance(TaskInstance ti, TextWriter tw)
        {
            JsonTextWriter jtw = new JsonTextWriter(tw);
            jtw.Formatting = Formatting.Indented;
            _ser.Serialize(jtw, ti);
            jtw.Flush();
        }

        public TaskInstance DeserializeTaskInstance(TextReader tr, Type taskType)
        {
            if (taskType == null)
            {
                return (TaskInstance) _ser.Deserialize(new JsonTextReader(tr));
            }
            else
            {
                return (TaskInstance)_ser.Deserialize(tr, taskType);
            }
        }
    }
}
